import { check } from 'meteor/check';
import { JoinServer } from 'meteor-publish-join';
import { ChannelMembers } from '/imports/models/ChannelMembers';

/**
 * 获取加入频道的所有成员
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.channel.members', function (query, limit) {
  check(query.id, String);
  check(limit, Number);

  const selector = {
    channel_id: query.id
  };

  const pipeline = [{
      $match: selector
    },
    {
      $sort: {
        createdAt: -1
      }
    },
    {
      $lookup: {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'users'
      }
    },
    {
      $addFields: {
        user: {
          $arrayElemAt: ["$users", 0]
        }
      }
    },
    {
      $project: {
        users: 0,
        'user.services': 0
      }
    },
    {
      $limit: limit
    }
  ];

  JoinServer.publish({
    context: this,
    name: 'get.channel.members.counts',
    interval: 0,
    doJoin() {
      return ChannelMembers.find(selector).count();
    }
  });

  ReactiveAggregate(this, ChannelMembers, pipeline, {
    clientCollection: 'clientChannelMembers'
  });
});
